<?php
namespace app\common\tool\profit_sharing;

class GroupBuyingMultiple extends Multiple {
	protected $order = null;
	protected $model = null;
	protected $groupBuyingLvEnum = null;
	protected $incomeLogTypeEnum = null;
	protected $receivers = [];
	protected $incomeLog = [];
	protected $incomeLogTypeOptions = null;
	protected $commission = 0;
	protected $systemCommission = 0;

	public function init($order) {
		$this->order = $order;
		$this->model = loadModel('tyyh\\GroupBuying');
		$this->groupBuyingLvEnum = loadEnum('GroupBuyingLv');
		$this->incomeLogTypeEnum = loadEnum('IncomeLogType');
		$this->incomeLogTypeOptions = $this->incomeLogTypeEnum->get_options();
		$this->systemCommission = $this->commission = $order['commission'] * 100;
	}

	//分账
	public function share($order) {
        $groupBuyingPromotionModel = loadModel('tyyh\\GroupBuyingPromotion');
        try {
            $this->init($order);

            $groupBuyingPromotionModel->startTrans();
            $groupBuyingPromotionModel->where(['oid' => $order['id']])->update([
                'status'     => loadEnum('GroupBuyingPromotionStatus')->code2key('yifenyong'),
                'updatetime' => time()
            ]);
            
            $spreadid = $order->getData('spreadid');
            if($spreadid + 0 > 0) {
                $this->add_tuangouyijifenyong($order, $spreadid);
            }
            $this->add_xitongshouru($order);
            $this->add_shangpinxiaoshoushouru($order);
            $this->multiple($order, $this->receivers, $this->incomeLog);
            $groupBuyingPromotionModel->commit();
        } catch (\Exception $e) {
            $groupBuyingPromotionModel->rollback();
            throw $e;
        }
	}

	//添加团购分佣
	public function add_tuangouyijifenyong($order, $spreadid) {
    	$row = $this->model->where(['uid' => $spreadid])->find();
        $type = $this->incomeLogTypeEnum->code2key('tuangouyijifenyong');
        $rate = $this->groupBuyingLvEnum->code2rate('tuanzhang');
        $fee = floor($this->commission * $rate / 100);
        if($fee > 0) {
            $this->receivers[] = $this->group_buying_user($spreadid, $fee, $this->incomeLogTypeOptions[$type]);
        }
        $this->systemCommission = $this->systemCommission - $fee;
        $this->add_income_log($spreadid, $order['id'], $type, $fee / 100);

        if($row['puid'] + 0 > 0) {
            $this->add_tuangouerjifenyong($row['puid']);
        }

	}

	//添加团购二级分佣
	public function add_tuangouerjifenyong($puid) {
		$row = $this->model->where(['uid' => $puid])->find();
        if($row && $row['lv'] >= 1) {
            $type = $this->incomeLogTypeEnum->code2key('tuangouerjifenyong');
            $rate = $this->groupBuyingLvEnum->code2rate('jingli');
            $fee = floor($this->commission * $rate / 100);
            if($fee > 0) {
                $this->receivers[] = $this->group_buying_user($puid, $fee, $this->incomeLogTypeOptions[$type]);
            }
            $this->systemCommission = $this->systemCommission - $fee;
            $this->add_income_log($puid, $order['id'], $type, $fee / 100);

            if($row['puid'] + 0 > 0) {
            	$this->add_tuangousanjifenyong($row['puid']);
            }
        }
	}

	//添加团购三级分佣
	public function add_tuangousanjifenyong($puid) {
		$row = $this->model->where(['uid' => $puid])->find();
        if($row && $row['lv'] >= 2) {
            $type = $this->incomeLogTypeEnum->code2key('tuangousanjifenyong');
            $rate = $this->groupBuyingLvEnum->code2rate('zongjian');
            $fee = floor($this->commission * $rate /100);
            if($fee > 0) {
                $this->receivers[] = $this->group_buying_user($puid, $fee, $this->incomeLogTypeOptions[$type]);
            }
            $this->systemCommission = $this->systemCommission - $fee;
            $this->add_income_log($puid, $order['id'], $type, $fee / 100);
        }
	}

	//添加系统收入
	public function add_xitongshouru($order) {
		$system = config('wechat.system');
        $type = $this->incomeLogTypeEnum->code2key('xitongshouru');
        $this->receivers[] = [
            'type'              => 'MERCHANT_ID',
            'receiver_account'  => $system['sub_mch_id'],
            'amount'            => $this->systemCommission,
            'description'       => $this->incomeLogTypeOptions[$type]
        ];
        $this->add_income_log(0, $order['id'], $type, $this->systemCommission / 100);
	}

	//添加商品销售收入记录
	public function add_shangpinxiaoshoushouru($order) {
		$type = $this->incomeLogTypeEnum->code2key('shangpinxiaoshoushouru');
        $store = loadModel('tysj\\Store')->find($order['sid']);
        if(empty($store)) {
            $this->error('店铺不存在');
        }
        $this->add_income_log($store['uid'], $order['id'], $type, $order['total_fee'] - $order['commission']);
	}

	//添加一条收入记录
	public function add_income_log($uid, $oid, $type, $fee) {
		$remark = $this->incomeLogTypeOptions[$type];
		$this->incomeLog[] = [
			'uid'      =>  $uid,
			'oid'      =>  $oid,
			'type'     =>  $type,
			'fee'      =>  $fee,
			'type'     =>  $type
		];
	}
}